# coding: utf-8
__author__ = 'j.tommy'
'''
实体类定义。
'''
import time
import uuid
from config import app_configs
from flask_sqlalchemy import SQLAlchemy
from flask import Flask

# 初始化
db = SQLAlchemy()


def create_app():
    app = Flask(__name__)
    db_config = app_configs['db']

    # dialect+driver://username:password@host:port/database?charset=utf8
    # 配置 sqlalchemy 数据库驱动://数据库用户名:密码@主机地址:端口/数据库?编码
    db_str = 'mysql+mysqlconnector://%s:%s@%s:%d/%s?charset=utf8' % (
        db_config['user'], db_config['password'], db_config['host'], db_config['port'], db_config['database'])
    print db_str
    app.config['SQLALCHEMY_DATABASE_URI'] = db_str

    db.init_app(app)
    db.create_all(app=app)
    return app


def next_id(t=None):
    """
    生成一个唯一id   由 当前时间 + 随机数（由伪随机数得来）拼接得到
    """
    if t is None:
        t = time.time()
    return '%015d%s000' % (int(t * 1000), uuid.uuid4().hex)


class User(db.Model):
    __tablename__ = 'user'

    id = db.Column(db.String(50), primary_key=True, default=next_id)
    user_id = db.Column(db.String(50))
    username = db.Column(db.String(50))
    password = db.Column(db.String(32))
    user_image = db.Column(db.String(500))
    name = db.Column(db.String(50))
    summary = db.Column(db.String(200))
    email = db.Column(db.String(500))
    created_at = db.Column(db.Float, default=time.time)

    def __repr__(self):
        return "<Uesr(user_id='%s',user_name='%s',name='%s',summary='%s',email='%s',created_at='%s')>" % (
            self.user_id, self.username, self.name, self.summary, self.email, self.created_at)


    def save(self):
        db.session.add(self)
        db.session.commit()


class Blog(db.Model):
    __tablename__ = 'blog'

    id = db.Column(db.String(50), primary_key=True, default=next_id)
    username = db.Column(db.String(50))
    title = db.Column(db.String(50))
    content = db.Column(db.String(10000))
    created_at = db.Column(db.Float, default=time.time)

    def __init__(self, username, title, content):
        self.username = username
        self.title = title
        self.content = content

    def save(self):
        # 后台不设置值，传到页面会显示为None。在保存时就是None.
        if self.id is None or self.id == 'None':
            self.id = None
            db.session.add(self)
            db.session.commit()
        else:
            blog = Blog.query.filter_by(id=self.id).first()
            blog.title = self.title
            blog.content = self.content
            blog.created_at = time.time()
            db.session.commit()


    def delete(self):
        db.session.delete(self)
        db.session.commit()


class Comment(db.Model):
    __tablename__ = 'comment'

    id = db.Column(db.String(50), primary_key=True, default=next_id)
    blog_id = db.Column(db.String(50))
    user_id = db.Column(db.String(50))
    content = db.Column(db.String(500))
    created_at = db.Column(db.Float, default=time.time)


class Page(object):
    def __init__(self, page):
        self.page = page
        self.show_pages = range(self.page.page, self.page.pages)